using UnityEngine;

public class LiquidSpawner : MonoBehaviour
{
	private Transform liquidLevelZero;

	private GlassFillingUpController glassFillingUpController;

	private DrinkTargets drinkTargets;

	private void Awake()
	{
		DefineConnections();
	}

	public Liquid SetLiquid(LiquidType liquidType)
	{
		Liquid lastLiquid = glassFillingUpController.GetLastLiquid();
		Liquid liquid = null;
		if (lastLiquid != null)
		{
			if (!lastLiquid.IsLiquidPoured())
			{
				if (lastLiquid.type == liquidType)
				{
					return null;
				}
				DestroyLastLiquid();
				lastLiquid = glassFillingUpController.GetLastLiquid();
			}
			if (lastLiquid != null)
			{
				if (lastLiquid.type == liquidType)
				{
					return null;
				}
				Vector3 liquidUpperPosition = lastLiquid.GetLiquidUpperPosition();
				liquidUpperPosition.z += 0.1f;
				return SpawnLiquid(liquidType, liquidUpperPosition);
			}
		}
		if (lastLiquid == null)
		{
			return SpawnLiquid(liquidType, liquidLevelZero.position);
		}
		return null;
	}

	private Liquid SpawnLiquid(LiquidType liquidType, Vector3 spawnPosition)
	{
		GameObject original = Resources.Load("Prefabs/Liquids/LiquidInGlass") as GameObject;
		GameObject gameObject = UnityEngine.Object.Instantiate(original, liquidLevelZero);
		gameObject.name = LiquidTypes.GetLiquidName(liquidType);
		gameObject.transform.position = spawnPosition;
		gameObject.GetComponent<Liquid>().SetLiquidTypeAndLiquidMaterial(liquidType);
		gameObject.GetComponent<Liquid>().SetLiquidLimitPosition(drinkTargets.GetMaxLiquidPosition());
		return gameObject.GetComponent<Liquid>();
	}

	private void DestroyLastLiquid()
	{
		glassFillingUpController.RemoveEmptyLastLiquid();
	}

	private void DefineConnections()
	{
		liquidLevelZero = base.transform.FindDeepChild("LiquidLevelZero");
		glassFillingUpController = GetComponent<GlassFillingUpController>();
		drinkTargets = GetComponent<DrinkTargets>();
	}
}
